<template>
  <!-- 申购审批详情 -->
  <base-page-view :class-name="'approval-detail ' + ((type === 'approval'&&approvalData.approval_status===1) ? 'hasFooter' : '')">
    <template v-if="pageLoaded">
      <view class="header" :class="{reject: approvalData.approval_status === 3 || approvalData.approval_status === 4}">
        <view>
          <view class="flex-wrapper">
            <b-image class-name="icon" :src="'/static/images/box/icon_state_'+statusObj[approvalData.approval_status]+'.png'" mode="aspectFit" :is-asset="true" />
            <view class="stateText">
              {{ approvalObj[approvalData.approval_status] }}
              <template v-if="approvalData.approval_status === 3 && approvalData.reject_reason">（原因：{{ approvalData.reject_reason }}）</template>
            </view>
          </view>
          <template v-if="type === 'purchase'">
            <view v-if="purchaseSubText[approvalData.approval_status]" class="sub">{{ purchaseSubText[approvalData.approval_status] }}</view>
            <view v-else-if="approvalData.approvaled_at" class="sub">审批时间：{{ approvalData.approvaled_at * 1000 | formatDate }}</view>
          </template>
          <view v-else-if="approvalData.approvaled_at" class="sub">审批时间：{{ approvalData.approvaled_at * 1000 | formatDate }}</view>
        </view>
      </view>
      <view v-if="type==='purchase'" class="block">
        <view class="block-title">审批人信息</view>
        <view class="line">
          <view class="label">手机号</view>
          <view class="value phone-value" @click="$callPhone(approvalData.approval_mobile)">
            <view>{{ approvalData.approval_mobile }}</view>
            <b-image class-name="icon" src="/static/images/box/icon_phone.png" mode="aspectFit" :is-asset="true" />
          </view>
        </view>
        <view class="line">
          <view class="label">审批人昵称</view>
          <view class="value">{{ approvalData.approval_nickname }}</view>
        </view>
      </view>
      <view class="block">
        <view v-for="(item, index) in approvalData.box_apply_goods_d_t_o_s" :key="index" class="goods-item">
          <b-image class-name="img" :src="item.image" />
          <view class="detail">
            <view>
              <view class="name">{{ item.goods_name }}</view>
              <!-- <view class="stock">当前我的云仓库存 {{ item.stock_number }}</view> -->
            </view>
            <view class="between-wrapper">
              <view class="price">{{ item.goods_price | formatMoney }}</view>
              <view class="number">{{ item.goods_number }}</view>
            </view>
          </view>
        </view>
      </view>
      <view v-if="type==='approval'" class="block">
        <view class="line">
          <view class="label">申购人昵称</view>
          <view class="value">{{ approvalData.apply_nickname }}</view>
        </view>
        <view class="line">
          <view class="label">申购人电话</view>
          <view class="value phone-value" @click="$callPhone(approvalData.apply_mobile)">
            <view>{{ approvalData.apply_mobile }}</view>
            <b-image class-name="icon" src="/static/images/box/icon_phone.png" mode="aspectFit" :is-asset="true" />
          </view>
        </view>
      </view>
      <view class="block">
        <view class="line between">
          <view class="label">
            <view>商品总额</view>
            <image class="icon" src="/static/images/common/icon_rule.png" mode="aspectFit" @click.stop="showWarn()" />
          </view>
          <view class="value price market-price">{{ approvalData.goods_total_amt | formatMoney }}</view>
        </view>
        <view class="line between">
          <view class="label">运费</view>
          <view class="value">提货时，按实际发生的运费进行收取</view>
        </view>
        <view class="line between">
          <view class="label">实际付款</view>
          <view class="value price">0.00</view>
        </view>
      </view>
      <view class="block">
        <view class="line">
          <view class="label">申购单号</view>
          <view class="value">{{ approvalData.apply_no }}</view>
          <view class="btn" @click="copy">复制</view>
        </view>
        <view class="line">
          <view class="label">申购时间</view>
          <view class="value">{{ approvalData.created_at*1000 | formatDate }}</view>
        </view>
        <view class="line">
          <view class="label">买家留言</view>
          <view class="value">{{ approvalData.apply_remark || '无' }}</view>
        </view>
      </view>
      <footer-bar v-if="type === 'approval'&&approvalData.approval_status===1">
        <view class="footer">
          <view class="btn" @click.stop="btnClick(3)">驳回</view>
          <view v-if="approvalData.stock_number_to_add > 0" class="btn main" @click.stop="btnClick(1)">
            <view>补库存(差{{ approvalData.stock_number_to_add }}箱)</view>
          </view>
          <view v-else class="btn main" @click.stop="btnClick(2)">通过</view>
        </view>
      </footer-bar>
      <view v-if="type === 'purchase'&&approvalData.approval_status===1" class="cancel-btn" @click="cancelPurchase">撤销申购</view>

      <confirm-popup ref="confirm">
        <template slot="content">
          <view v-if="handleObj.approvalStatus===3" class="reject-block">
            <view class="title">选择理由</view>
            <view class="content">
              <view class="type-item" @click="handleObj.rejectType = 1;handleObj.rejectReason='';handleObj.leastNum = 10">
                <image v-if="handleObj.rejectType === 1" src="/static/images/icon/icon_radio_active.png" mode="aspectFit" />
                <image v-else src="/static/images/icon/icon_radio.png" mode="aspectFit" />
                <view>未收到货款</view>
              </view>
              <view class="type-item" @click="handleObj.rejectType = 2">
                <image v-if="handleObj.rejectType === 2" src="/static/images/icon/icon_radio_active.png" mode="aspectFit" />
                <image v-else src="/static/images/icon/icon_radio.png" mode="aspectFit" />
                <view>其他</view>
              </view>
              <view class="input-item">
                <input v-model="handleObj.rejectReason" type="text" placeholder="请输入驳回理由" maxlength="10" :disabled="handleObj.rejectType === 1" @input="inputChange" />
                <view class="number">{{ handleObj.leastNum }}</view>
              </view>
            </view>
          </view>
          <view v-else-if="handleObj.approvalStatus===2" class="pass-warn-block">
            <view>为保障您的权益~</view>
            <view class="warn">请确认您<text>已线下收到了货款</text></view>
            <view>确认后云仓库存将扣减，划拨至申购人的云仓中。~</view>
            <view class="bg">*未收到货款前，请不要点击确认！</view>
          </view>
        </template>
      </confirm-popup>
    </template>
  </base-page-view>
</template>
<script>
import footerBar from '@/components/footerBar/index'
import confirmPopup from '@/components/confirmPopup/index'
import { formatUrlParam, setClipboardData } from '@/utils/tools'
import './detail.scss'
export default {
  name: 'ApprovalDetail',
  components: {
    footerBar,
    confirmPopup
  },
  data() {
    return {
      pageLoaded: false,
      createOrderPermission: false,
      titleObj: {
        approval: '审批',
        purchase: '申购订单详情'
      },
      approvalObj: {},
      purchaseSubText: ['', '申购已提交成功', '已将商品加至您的云仓中', '', '该申购单已撤销，请重新发起申购'],
      statusObj: {
        '1': 'approval',
        '2': 'complete',
        '3': 'reject',
        '4': 'cancel'
      },
      type: 'approval',
      id: '',
      approvalData: {
        box_apply_goods_d_t_o_s: []
      },
      handleObj: {
        id: '',
        approvalStatus: '', // 审批状态：2-审批通过，3-审批驳回
        rejectType: 1,
        rejectReason: '',
        leastNum: 10
      }
    }
  },
  onLoad(options) {
    this.type = options.type
    if (this.type === 'approval') {
      this.approvalObj = {
        '1': '待审批',
        '2': `审批已通过`,
        '3': `审批已驳回`,
        '4': '已撤销'
      }
    } else {
      this.approvalObj = {
        '1': '待审批',
        '2': `已完成`,
        '3': `审批已驳回`,
        '4': '已撤销'
      }
    }
    this.id = options.id
    this.createOrderPermission = this.userInfo && this.userInfo.boxPermission && this.userInfo.boxPermission.includes(2)
    this.$setNavTitle(this.titleObj[this.type])
    if (this.id) {
      this.fetchData()
    }
  },
  methods: {
    async fetchData() {
      const res = await this.$api.boxApi.getApprovalDetail({ id: this.id })
      if (res.success && res.data) {
        const i = res.data
        const flag = i.box_apply_goods_d_t_o_s && i.box_apply_goods_d_t_o_s.length
        const goods = flag ? i.box_apply_goods_d_t_o_s[0] : {}
        const stock = goods.stock_number || 0
        const num = goods.goods_number || 0
        const stock_number_to_add = (num - stock) > 0 ? (num - stock) : 0
        this.approvalData = {
          ...res.data,
          stock_number_to_add
        }
        console.log(res.data)
      }
      this.pageLoaded = true
    },
    inputChange(e) {
      if (e.detail && e.detail.value !== '') {
        this.handleObj.rejectReason = e.detail.value
        this.handleObj.leastNum = (10 - e.detail.value.length)
      } else {
        this.handleObj.leastNum = 10
      }
    },
    showWarn() {
      uni.showToast({ title: '线下支付', icon: 'none' })
    },
    async btnClick(type, index) {
      // type 1:补库存， 2:通过，3:驳回
      const item = this.approvalData
      if (type === 1) {
        const params = {}

        const settleData = {
          shopping_list: JSON.stringify([{
            num: item.stock_number_to_add,
            goods_id: item.box_apply_goods_d_t_o_s[0].goods_id,
            sku_code: item.box_apply_goods_d_t_o_s[0].goods_sku,
            goods_type: 1,
            from_type: 11
          }]),
          new_box_order_type: 1,
          stock_goods_id: item.box_apply_goods_d_t_o_s[0].goods_id,
          stock_sku_code: item.box_apply_goods_d_t_o_s[0].goods_sku,
          is_used_coupon: 0
        }
        if (this.createOrderPermission) {
          params.boxType = 'buy'
        } else {
          params.boxType = 'apply'
          this.$store.dispatch('setGoodsTemp', {
            shopping_list: settleData.shopping_list,
            data: {
              coupon_list: [],
              hongbao_list: [],
              unusable_coupon_list: [],
              shopping_items: {
                activity_item_list: [],
                item_list: [
                  {
                    goods_id: item.box_apply_goods_d_t_o_s[0].goods_id,
                    title: item.box_apply_goods_d_t_o_s[0].goods_name,
                    num: item.stock_number_to_add,
                    vip_price: item.box_apply_goods_d_t_o_s[0].goods_price,
                    sku_code: item.box_apply_goods_d_t_o_s[0].goods_sku,
                    pic: item.box_apply_goods_d_t_o_s[0].image,
                    stock_number: item.box_apply_goods_d_t_o_s[0].stock_number,
                    need_change_num: true
                  }
                ]
              }
            },
            settleData
          })
          this.$navigateTo(formatUrlParam('/pagesBox/pick-up/index', {
            boxType: 'apply'
          }))
          return
        }
        const resSettle = await this.$api.orderApi.orderSettle(settleData)
        if (resSettle.success) {
          this.$store.dispatch('setGoodsTemp', {
            shopping_list: settleData.shopping_list,
            data: resSettle.data,
            settleData
          })
          this.$navigateTo(formatUrlParam('/pagesBox/pick-up/index', params))
        }
      } else {
        this.handleObj = {
          id: item.id,
          approvalStatus: type, // 审批状态：2-审批通过，3-审批驳回
          rejectType: 1,
          rejectReason: '',
          leastNum: 10
        }
        const title = ['', '', '温馨提示', '驳回确认'][type]
        const cancleTxt = ['', '', '我再想想', '取消'][type]
        const yesTxt = ['', '', '我确定', '提交'][type]
        const duration = type === 2 ? 5000 : 0
        this.$refs.confirm.show({
          title,
          cancleTxt,
          yesTxt,
          duration,
          maskClickClose: false,
          yesCb: async() => {
            const postData = { ...this.handleObj }
            if (postData.approvalStatus === 3 && postData.rejectType === 1) {
              postData.rejectReason = '未收到货款'
            }
            const res = await this.$api.boxApi.operateApproval(postData)
            if (res.success) {
              uni.showToast({ title: '操作成功', icon: 'none' })
              this.fetchData()
            }
          }
        })
      }
    },
    cancelPurchase() {
      this.$refs.confirm.show({
        title: '提示',
        content: '撤销后该申购订单将作废',
        yesCb: async() => {
          const res = await this.$api.boxApi.revokePurchase({
            applyId: this.approvalData.id,
            applyUserId: this.approvalData.apply_user_id
          })
          if (res.success) {
            this.fetchData()
            uni.showToast({
              title: '撤销成功',
              icon: 'none',
              duration: 2000,
              mask: true
            })
          }
        }
      })
    },
    copy() {
      if (this.approvalData.apply_no) {
        setClipboardData({
          data: this.approvalData.apply_no,
          success: () => {
            uni.showToast({
              title: '复制成功',
              icon: 'none',
              duration: 1500
            })
          }
        })
      }
    }
  }
}
</script>
